package com.ow.dva.config;

import cn.hutool.core.io.FileUtil;
import com.ow.dva.config.constant.CorsConstant;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;

import java.io.IOException;

/**
 * 描述 : 解决跨域和部分映射问题
 * 包名 : com.ow.dva.config.handler
 *
 * @author GaoXiang
 * @version V1.1
 * @since 19-5-8
 */
@Configuration
public class WebApiConfiguration extends WebMvcConfigurationSupport {

    @Value("${dva.static-path}")
    private String staticPath;

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        String t0="",t1="",t2="";
        // 配置路径
        try {
            if(staticPath.equals("auto")){
                staticPath = FileUtil.file(".", "/").getCanonicalPath();
                t0 = staticPath + "/upload";
                t1 = staticPath + "/wx-pay-code";
                t2 = staticPath + "/version";
                System.out.println(t1);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        //处理静态文件
        /*registry.addResourceHandler("/static/**")
                .addResourceLocations("file:" + staticPath);*/
        registry.addResourceHandler("/**")
                .addResourceLocations("classpath:/static/");

        registry.addResourceHandler("/upload/**")
                .addResourceLocations("file:"+t0+"/");

        registry.addResourceHandler("/wx-pay-code/**")
                .addResourceLocations("file:"+t1+"/");

        registry.addResourceHandler("/version/**")
                .addResourceLocations("file:"+t2+"/");
        //处理swagger-ui
        registry.addResourceHandler("swagger-ui.html")
                .addResourceLocations("classpath:/META-INF/resources/");
        registry.addResourceHandler("doc.html")
                .addResourceLocations("classpath:/META-INF/resources/");
        //处理jar包
        registry.addResourceHandler("/webjars/**")
                .addResourceLocations("classpath:/META-INF/resources/webjars/");

        super.addResourceHandlers(registry);
    }

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping(CorsConstant.REGISTER_URL)
                .allowedOrigins(CorsConstant.ALLOWED_ORIGIN)
                .allowedHeaders(CorsConstant.ALLOWED_HEADER)
                .allowedMethods(CorsConstant.ALLOWED_METHOD)
                .allowCredentials(true).maxAge(3600);
    }
}
